const cheerio = require('cheerio')
const fs = require('fs')
const path = require('path')
const Fontmin = require('fontmin')

const html = fs.readFileSync(path.join(__dirname, 'dist/index.html'))

const $ = cheerio.load(html.toString('utf8'))

const characters = $('body').text().replace(/\s+/g, '')
const text = Array.from(new Set(characters.split(''))).join('')

new Fontmin()
    .use(Fontmin.glyph({ text: text }))
    .src(path.join(__dirname, 'dist/fonts/serif.ttf'))
    .dest(path.join(__dirname, 'dist/fonts'))
    .run((err, files) => {
        if (err) {
            throw err
        }

        const originSize = fs.statSync(path.join(__dirname, 'src/fonts/serif.ttf')).size
        const compressedSize = fs.statSync(path.join(__dirname, 'dist/fonts/serif.ttf')).size

        console.log('页面总计使用字数:', text.length)
        console.log('原始字体文件大小:', (originSize / 1024 / 1024).toFixed(2) + 'MB')
        console.log('压缩字体文件大小:', (compressedSize / 1024 / 1024).toFixed(2) + 'MB')
    })
